package algo.array;

public class Array {
    private int data[];
    // 数组长度
    private int n;
    // 实际个数
    private int count;

    public Array(int capacity) {
        this.data = new int[capacity];
        this.n = capacity;
        this.count = 0;
    }

    public int find(int index) {
        if (index <0 || index >= count) {
            return -1;
        }
        return data[index];
    }

    public boolean insert(int index, int value) {
        // 数组空间已满
        if (count == n) {
            System.out.println("没有可插入的位置");
            return false;
        }

        if (count < 0 || index > count) {
            System.out.println("位置不合法");
             return false;
        }

        for (int i = count; i > index; --i) {
            data[i] = data[i-1];
        }
        data[index] = value;
        ++count;
        return true;
    }

    /**
     * 删除元素
     * @param index
     * @return
     */
    public boolean delete(int index) {
        if (index <0 || index >= count) {
            return false;
        }
        // 从删除位置开始，将后面的元素向前移动一位
        for (int i = index + 1; i< count;++i) {
            data[i-1] =data[i];
        }
        --count;
        // 删除末尾的元素，这一段不要也可以
        int[] newArr = new int[count];
        for (int i = 0; i < count; ++i) {
            newArr[i] = data[i];
        }
        this.data = newArr;


        return true;
    }

    private void printAll() {
        for (int i = 0; i < count; i++) {
            System.out.print(data[i] + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        Array array = new Array(5);
        array.insert(0, 5);
        array.insert(1, 4);

        array.printAll();

        array.delete(0);
        array.printAll();

        System.out.println(array.find(1));
        System.out.println(array.find(0));
    }
}
